Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 12180 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
Line 
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:
25 *      Johannes Ritz
26 *
27 *
28 *
29 *
30 *TASK c) end the game in a nicer way
31 *TASK d) save the highscore
32 *TASK e) eye candy
33 */
34
35/**
36    @file Tetris.cc
37    @brief Implementation of the Tetris class.
38*/
39
40#include "Tetris.h"
41#include "Highscore.h"
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"
51#include "TetrisBrick.h"
52#include "infos/PlayerInfo.h"
53#include <cmath>
54
55namespace orxonox
56{
57
58    RegisterUnloadableClass(Tetris);
59
60    /**
61    @brief
62        Constructor. Registers and initializes the object.
63    @ingroup Tetris
64    */
65    Tetris::Tetris(Context* context) : Deathmatch(context)
66    {
67        RegisterObject(Tetris);
68
69        this->activeBrick_ = nullptr;
70
71        // Pre-set the timer, but don't start it yet.
72        this->starttimer_.setTimer(1.0, false, createExecutor(createFunctor(&Tetris::startBrick, this)));
73        this->starttimer_.stopTimer();
74
75        this->player_ = nullptr;
76        this->setHUDTemplate("TetrisHUD");
77        this->futureBrick_ = nullptr;
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    {
96        if (this->activeBrick_)
97        {
98            this->activeBrick_->destroy();
99            this->activeBrick_ = nullptr;
100        }
101        if (this->futureBrick_)
102        {
103            this->futureBrick_->destroy();
104            this->futureBrick_ = nullptr;
105        }
106
107        for (TetrisStone* stone : this->stones_)
108            stone->destroy();
109        this->stones_.clear();
110    }
111
112    void Tetris::tick(float dt)
113    {
114        SUPER(Tetris, tick, dt);
115
116        if((this->activeBrick_ != nullptr)&&(!this->hasEnded()))
117        {
118            if(!this->isValidBrickPosition(this->activeBrick_))
119            {
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();
126            }
127        } 
128    }
129
130    bool Tetris::isValidMove(TetrisStone* stone, const Vector3& position)
131    {
132        assert(stone);
133
134        if(position.x < this->center_->getStoneSize()/2.0)  //!< If the stone touches the left edge of the level
135            return false;
136        else if(position.x > (this->center_->getWidth()-0.5)*this->center_->getStoneSize()) //!< If the stone touches the right edge of the level
137            return false;
138
139        for(TetrisStone* someStone : this->stones_)
140        {
141            const Vector3& currentStonePosition = someStone->getPosition(); //!< Saves the position of the currentStone
142
143            if((position.x == currentStonePosition.x) && std::abs(position.y-currentStonePosition.y) < this->center_->getStoneSize())
144                return false;
145        }
146
147        return true;
148    }
149
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
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)
191    {
192        assert(stone);
193
194        // check for collisions with all stones
195        for(TetrisStone* someStone : this->stones_)
196        {
197            //Vector3 currentStonePosition = rotateVector((*it)->getPosition(), this->activeBrick_->getRotationCount());
198            const Vector3& currentStonePosition = someStone->getPosition(); //!< Saves the position of the currentStone
199
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;
203            if((position.x == currentStonePosition.x) && (position.y < currentStonePosition.y + this->center_->getStoneSize()))
204            {
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));
209                return false;
210            }// This case applies if the stones overlap partially vertically
211        }
212
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);
223        if(position.y < this->center_->getStoneSize()/2.0f) //!< If the stone has reached the bottom of the level
224        {
225            float baseOffset = std::abs(stone->getPosition().y);
226            if (this->activeBrick_->getRotationCount() == 1 || this->activeBrick_->getRotationCount() == 3)
227                baseOffset = std::abs(stone->getPosition().x);
228            float yOffset = baseOffset + this->center_->getStoneSize()/2.0f;//calculate offset
229            if(yOffset < 0) //catch brake-throughs
230                yOffset = 0;
231            this->activeBrick_->setPosition(Vector3(this->activeBrick_->getPosition().x, yOffset, this->activeBrick_->getPosition().z));
232            return false;
233        }
234        return true;
235    }
236   
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);
244
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());
252            if(! this->checkStoneStoneCollision(stone, brickPosition + stonePosition) )
253            {
254                return false;
255            }
256        }
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       
268        return true;
269    }
270
271    /**
272    @brief
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
289        Starts the Tetris minigame.
290    */
291    void Tetris::start()
292    {
293        if (this->center_ != nullptr) // There needs to be a TetrisCenterpoint, i.e. the area the game takes place.
294        {
295            // Create the first brick.
296            this->createBrick();
297        }
298        else // If no centerpoint was specified, an error is thrown and the level is exited.
299        {
300            orxout(internal_error) << "Tetris: No Centerpoint specified." << endl;
301            GSLevel::startMainMenu();
302            return;
303        }
304
305        // Start the timer. After it has expired the stone is started.
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    {
325        this->activeBrick_->setVelocity(Vector3::ZERO);
326        if(this->activeBrick_ != nullptr)
327        {
328            this->player_->stopControl();
329        }
330        if (Highscore::exists())
331        {
332            int score = this->getScore(this->getPlayer());
333            Highscore::getInstance().storeScore("Tetris", score, this->getPlayer());
334        }
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.
348        for (const auto& mapEntry : this->players_)
349            if (mapEntry.first->isHumanPlayer() && (mapEntry.first->isReadyToSpawn() || this->bForceSpawn_))
350                this->spawnPlayer(mapEntry.first);
351    }
352   
353    bool Tetris::playerLeft(PlayerInfo* player)
354    {
355        bool left = Gametype::playerLeft(player);
356        if(player && player->isHumanPlayer())
357        {
358            if(this->activeBrick_ != nullptr)
359            {
360                this->player_->stopControl();
361            }
362            this->cleanup();
363        }
364        return left;
365    }
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
377        if(this->player_ == nullptr)
378        {
379            this->player_ = player;
380            this->players_[player].state_ = PlayerState::Alive;
381        }
382    }
383
384
385
386    void Tetris::startBrick(void)
387    {
388        if(this->player_ == nullptr)
389            return;
390
391        unsigned int cameraIndex = 0;
392        if(this->activeBrick_ != nullptr)
393        {
394            // Get camera settings
395            cameraIndex = this->activeBrick_->getCurrentCameraIndex();
396            this->player_->stopControl();
397            // destroy old active brick
398            this->activeBrick_->destroy();
399        }
400
401        // Make the last brick to be created the active brick.
402        this->activeBrick_ = this->futureBrick_;
403        this->futureBrick_ = nullptr;
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();
419    }
420
421    void Tetris::createBrick(void)             //TODO: random rotation offset between 0 and 3 (times 90°)
422    {
423        // create new futureBrick_
424        this->futureBrick_ = new TetrisBrick(this->center_->getContext());
425
426
427        // Apply the stone template to the stone.
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();
434       
435        this->futureBrick_->setPosition(xPos, yPos, 0.0f);
436        this->futureBrick_->setGame(this);
437    }
438
439
440    /**
441    @brief
442        Get the player.
443    @return
444        Returns a pointer to the player. If there is no player, nullptr is returned.
445    */
446    PlayerInfo* Tetris::getPlayer(void) const
447    {
448        return this->player_;
449    }
450
451    /*TetrisCenterpoint* Tetris::getCenterpoint(void) const
452    {
453        return this->center_;
454    }*/
455
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
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;
476            for(std::list<StrongPtr<TetrisStone>>::iterator it = this->stones_.begin(); it != this->stones_.end(); )
477            {
478                std::list<StrongPtr<TetrisStone>>::iterator it_temp = it++;
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
498        for(std::list<StrongPtr<TetrisStone>>::iterator it = this->stones_.begin(); it != this->stones_.end(); )
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.
509        for(TetrisStone* stone : this->stones_)
510        {
511            if(static_cast<unsigned int>((stone->getPosition().y - 5)/this->center_->getStoneSize()) > row)
512                stone->setPosition(stone->getPosition()-Vector3(0,10,0));
513        }
514
515    }
516
517
518}
Note: See TracBrowser for help on using the repository browser.