Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 11597 was 11356, checked in by patricwi, 8 years ago

merged space race with trunk

  • Property svn:eol-style set to native
File size: 16.6 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                    int score = this->getScore(this->getPlayer());
332                    if(score > Highscore::getInstance().getHighestScoreOfGame("Tetris")) 
333                        Highscore::getInstance().storeHighscore("Tetris",score);
334
335          }
336        this->cleanup();
337
338        // Call end for the parent class.
339        Deathmatch::end();
340    }
341
342    /**
343    @brief
344        Spawns player.
345    */
346    void Tetris::spawnPlayersIfRequested()
347    {
348        // Spawn a human player.
349        for (const auto& mapEntry : this->players_)
350            if (mapEntry.first->isHumanPlayer() && (mapEntry.first->isReadyToSpawn() || this->bForceSpawn_))
351                this->spawnPlayer(mapEntry.first);
352    }
353   
354    bool Tetris::playerLeft(PlayerInfo* player)
355    {
356        bool left = Gametype::playerLeft(player);
357        if(player && player->isHumanPlayer())
358        {
359            if(this->activeBrick_ != nullptr)
360            {
361                this->player_->stopControl();
362            }
363            this->cleanup();
364        }
365        return left;
366    }
367
368    /**
369    @brief
370        Spawns the input player.
371    @param player
372        The player to be spawned.
373    */
374    void Tetris::spawnPlayer(PlayerInfo* player)
375    {
376        assert(player);
377
378        if(this->player_ == nullptr)
379        {
380            this->player_ = player;
381            this->players_[player].state_ = PlayerState::Alive;
382        }
383    }
384
385
386
387    void Tetris::startBrick(void)
388    {
389        if(this->player_ == nullptr)
390            return;
391
392        unsigned int cameraIndex = 0;
393        if(this->activeBrick_ != nullptr)
394        {
395            // Get camera settings
396            cameraIndex = this->activeBrick_->getCurrentCameraIndex();
397            this->player_->stopControl();
398            // destroy old active brick
399            this->activeBrick_->destroy();
400        }
401
402        // Make the last brick to be created the active brick.
403        this->activeBrick_ = this->futureBrick_;
404        this->futureBrick_ = nullptr;
405
406        // set its position
407        this->player_->startControl(this->activeBrick_);
408        float xPos = (this->center_->getWidth()/2 + ((this->center_->getWidth() % 2)*2-1)/2.0f)*this->center_->getStoneSize();
409        float yPos = (this->center_->getHeight()-0.5f)*this->center_->getStoneSize();
410        this->activeBrick_->setPosition(xPos, yPos, 0.0f);
411        this->activeBrick_->setVelocity(0.0f, -this->center_->getStoneSpeed(), 0.0f);
412        this->activeBrick_->setCameraPosition(cameraIndex);
413
414        // create a new future brick
415        this->createBrick();
416
417        // check if the new brick is in a valid position, otherwise end the game
418        if (!this->isValidBrickPosition(this->activeBrick_))
419            this->end();
420    }
421
422    void Tetris::createBrick(void)             //TODO: random rotation offset between 0 and 3 (times 90°)
423    {
424        // create new futureBrick_
425        this->futureBrick_ = new TetrisBrick(this->center_->getContext());
426
427
428        // Apply the stone template to the stone.
429        this->futureBrick_->addTemplate(this->center_->getBrickTemplate());
430
431        // Attach the brick to the Centerpoint and set the position of the brick to be at the left side.
432        this->center_->attach(this->futureBrick_);
433        float xPos = (this->center_->getWidth()*1.6f + ((this->center_->getWidth() % 2)*2-1)/2.0f)*this->center_->getStoneSize();
434        float yPos = (this->center_->getHeight()-5.1f)*this->center_->getStoneSize();
435       
436        this->futureBrick_->setPosition(xPos, yPos, 0.0f);
437        this->futureBrick_->setGame(this);
438    }
439
440
441    /**
442    @brief
443        Get the player.
444    @return
445        Returns a pointer to the player. If there is no player, nullptr is returned.
446    */
447    PlayerInfo* Tetris::getPlayer(void) const
448    {
449        return this->player_;
450    }
451
452    /*TetrisCenterpoint* Tetris::getCenterpoint(void) const
453    {
454        return this->center_;
455    }*/
456
457    /**
458    @brief Set the TetrisCenterpoint (the playing field).
459    @param center A pointer to the TetrisCenterpoint to be set.
460    */
461    void Tetris::setCenterpoint(TetrisCenterpoint* center)
462    {
463        this->center_ = center;
464    }
465
466    /**
467    @brief Check each row if it is full. Removes all full rows. Update
468    @brief Manages score.
469    */
470    void Tetris::findFullRows()
471    {
472        unsigned int correctPosition = 0;
473        unsigned int stonesPerRow = 0;
474        for (unsigned int row = 0; row < this->center_->getHeight(); row++)
475        {
476            stonesPerRow = 0;
477            for(std::list<StrongPtr<TetrisStone>>::iterator it = this->stones_.begin(); it != this->stones_.end(); )
478            {
479                std::list<StrongPtr<TetrisStone>>::iterator it_temp = it++;
480                correctPosition = static_cast<unsigned int>(((*it_temp)->getPosition().y - 5)/this->center_->getStoneSize());
481                if(correctPosition == row)
482                {
483                    stonesPerRow++;
484                    if(stonesPerRow == this->center_->getWidth())
485                    {
486                        clearRow(row);
487                        row--; //the row counter has to be decreased in order to detect multiple rows!
488                        this->playerScored(this->player_);// add points
489                        //increase the stone's speed
490                        this->center_->setStoneSpeed(this->center_->getStoneSpeed()+1.0f);
491                    }
492                }
493            }
494        }
495    }
496
497    void Tetris::clearRow(unsigned int row)
498    {// clear the full row
499        for(std::list<StrongPtr<TetrisStone>>::iterator it = this->stones_.begin(); it != this->stones_.end(); )
500        {
501            if(static_cast<unsigned int>(((*it)->getPosition().y - 5)/this->center_->getStoneSize()) == row)
502            {
503                (*it)->destroy();
504                this->stones_.erase(it++);
505            }
506            else
507                ++it;
508        }
509      // adjust height of stones above the deleted row //TODO: check if this could be a source of a bug.
510        for(TetrisStone* stone : this->stones_)
511        {
512            if(static_cast<unsigned int>((stone->getPosition().y - 5)/this->center_->getStoneSize()) > row)
513                stone->setPosition(stone->getPosition()-Vector3(0,10,0));
514        }
515
516    }
517
518
519}
Note: See TracBrowser for help on using the repository browser.