Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/towerdefenseFS15/src/modules/towerdefense/TowerDefense.cc @ 10406

Last change on this file since 10406 was 10406, checked in by fvultier, 9 years ago

There is now a cube that can be moved on the playground using the arrow keys.

  • Property svn:eol-style set to native
File size: 17.4 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 *      ...
26 *
27 *NACHRICHT:
28 *
29 * Hier empfehle ich euch die gesamte Spielogik unter zu bringen. Viele Funktionen werden automatisch
30 * bei gewissen Ereignissen aufgerufen bzw. lösen Ereignisse aus
31 *
32 *Z.B:
33 * start() //wird aufgerufen, bevor das Spiel losgeht
34 * end() //wenn man diese Funktion aufruft wird
35 * pawnKilled() // wird aufgerufen, wenn ein Pawn stirbt (z.B: wenn )
36 * playerScored() // kann man aufrufen um dem Spieler Punkte zu vergeben.
37 *
38 *
39 *TIPP: Eclipse hilft euch schnell auf bereits vorhanden Funktionen zuzugreifen:
40 * einfach "this->" eingeben und kurz warten. Dann tauch eine Liste mit Vorschlägen auf. Wenn ihr jetzt weiter
41 * tippt, werden die Vorschläge entsprechend gefiltert.
42 *
43 *
44 *TIPP: schaut euch mal Tetris::createStone() an. Dort wird ein TetrisStone-Objekt (ControllableEntity) erzeugt,
45 * ihm ein Template zugewiesen (welches vorher im Level definiert wurde und dem CenterPoint übergeben wurde)
46 * Ähnlich könnt ihr vorgehen, um einen Turm zu erzeugen. (Zusätzlich braucht ein Turm noch einen Controller)
47 * z.B: WaypointPatrolController. Wenn kein Team zugewiesen wurde bekämpft ein WaypointPatrolController alles,
48 * was in seiner Reichweite liegt.
49 *
50 *
51 *HUD:
52 * Ein Gametype kann ein HUD (Head up Display haben.) Z.B: hat Pong eine Anzeige welcher Spieler wieviele Punkte hat.
53 * Generell kann man a) Grafiken oder b) Zeichen in einer HUD anzeigen.
54 * Fuer den ersten Schritt reicht reiner Text.
55 *
56 * a)
57 * PongScore.cc uebernehmen und eigene Klasse draus machen.
58 * Wenn ihr bloss anzeigen wollt wieviele Punkte der Spieler bereits erspielt hat (Punkte = Kapital fuer neue Tuerme) dann orientiert ihr euch an
59 * TetrisScore.cc (im pCuts branch): http://www.orxonox.net/browser/code/branches/pCuts/src/modules/tetris/TetrisScore.cc
60 * Ich habe TetrisScore lediglich dazu gebraucht, um eine Variable auf dem HUD auszugeben. Ein Objekt fuer statischen Text gibt es bereits.
61 *
62 * b)
63 * Im naesten Schritt erstellt man die Vorlage fuer das HUD-Objekt: siehe /data/overlays/pongHUD
64 * OverlayText ist eine Vorlage fuer statischen text zb: "Points Scored:". Aus mir nicht erklaerlichen Gruenden sollte man die OverlayText
65 * Objekte immer erst nach dem PongScore anlegen.
66 *
67 * c)  Im TowerDefense gamtype muss im Constructor noch das HUD-Template gesetzt werden.
68 *
69 * d) in CMakeLists.txt noch das Module includen das fuer die Overlays zustaendig ist. Siehe das gleiche File im Pong module.
70 *
71 *
72 *
73 */
74#include "TowerDefense.h"
75#include "TowerDefenseTower.h"
76#include "TowerDefenseCenterpoint.h"
77//#include "TDCoordinate.h"
78#include "worldentities/SpawnPoint.h"
79#include "worldentities/pawns/Pawn.h"
80#include "worldentities/pawns/SpaceShip.h"
81#include "controllers/WaypointController.h"
82#include "graphics/Model.h"
83#include "infos/PlayerInfo.h"
84#include "chat/ChatManager.h"
85#include "core/CoreIncludes.h"
86/* Part of a temporary hack to allow the player to add towers */
87#include "core/command/ConsoleCommand.h"
88
89
90namespace orxonox
91{
92    static const std::string __CC_addTower_name  = "addTower";
93    static const std::string __CC_upgradeTower_name = "upgradeTower";
94
95    SetConsoleCommand("TowerDefense", __CC_addTower_name,  &TowerDefense::addTower ).addShortcut().defaultValues(1);
96    SetConsoleCommand("TowerDefense", __CC_upgradeTower_name, &TowerDefense::upgradeTower).addShortcut().defaultValues(0);
97
98    RegisterUnloadableClass(TowerDefense);
99
100    TowerDefense::TowerDefense(Context* context) : TeamDeathmatch(context)
101    {
102        RegisterObject(TowerDefense);
103/*
104        for (int i=0; i < 16 ; i++){
105            for (int j = 0; j< 16 ; j++){
106                towermatrix[i][j] = NULL;
107            }
108        }*/
109
110        selecter = NULL;
111        this->player_ = NULL;       
112        this->setHUDTemplate("TowerDefenseHUD");
113        this->nextwaveTimer_.setTimer(10, false, createExecutor(createFunctor(&TowerDefense::nextwave, this)));
114        this->nextwaveTimer_.stopTimer();
115        this->waves_ = 0;
116        this->time = 0;
117        this->credit_ = 0;
118        this->lifes_ = 0;
119
120        //this->stats_ = new TowerDefensePlayerStats();
121
122        ModifyConsoleCommand(__CC_addTower_name).setObject(this);
123        ModifyConsoleCommand(__CC_upgradeTower_name).setObject(this);
124    }
125
126    TowerDefense::~TowerDefense()
127    {
128        /* Part of a temporary hack to allow the player to add towers */
129        if (this->isInitialized())
130        {
131            ModifyConsoleCommand(__CC_addTower_name).setObject(NULL);
132            ModifyConsoleCommand(__CC_upgradeTower_name).setObject(NULL);
133        }
134    }
135
136    void TowerDefense::setCenterpoint(TowerDefenseCenterpoint *centerpoint)
137    {
138        orxout() << "Centerpoint now setting..." << endl;
139        this->center_ = centerpoint;
140        orxout() << "Centerpoint now set..." << endl;
141    }
142
143    void TowerDefense::start()
144    {
145        if (center_ != NULL) // There needs to be a TowerDefenseCenterpoint, i.e. the area the game takes place.
146        {
147            if (selecter == NULL)
148            {
149                selecter = new TowerDefenseSelecter(this->center_->getContext());               
150            }
151            selecter->addTemplate(center_->getSelecterTemplate());
152            center_->attach(selecter);
153        }
154        else // If no centerpoint was specified, an error is thrown and the level is exited.
155        {
156            orxout(internal_error) << "Jump: No Centerpoint specified." << endl;
157            return;
158        }
159
160        TeamDeathmatch::start();
161
162        // Waypoints: [1,3] [10,3] [10,11] [13,11] -> add the points to a matrix so the player cant place towers on the path
163        for (int i=0; i < 16 ; i++)
164        {
165            for (int j = 0; j< 16 ; j++)
166            {
167                towerModelMatrix[i][j] = NULL;
168                towerTurretMatrix[i][j] = NULL;
169            }
170        }
171
172       
173
174        if (player_ != NULL)
175        {
176            //this->player_->startControl(selecter);
177        }
178        else
179        {
180            orxout() << "player=NULL" << endl;
181        }
182
183
184        Model* dummyModel = new Model(this->center_->getContext());
185
186        //the path of the spacehips has to be blocked, so that no towers can be build there
187        for (int k=0; k<3; k++)
188            towerModelMatrix[1][k]=dummyModel;
189        for (int l=1; l<11; l++)
190                towerModelMatrix[l][3]=dummyModel;
191        for (int m=3; m<12; m++)
192                towerModelMatrix[10][m]=dummyModel;
193        for (int n=10; n<14; n++)
194                towerModelMatrix[n][11]=dummyModel;
195        for (int o=13; o<16; o++)
196                towerModelMatrix[13][o]=dummyModel;
197
198
199        //set initial credits, lifes and WaveNumber
200        this->setCredit(1000);
201        this->setLifes(100);
202        this->setWaveNumber(0);
203        time=0.0;
204
205        /*
206        //adds initial towers
207        for (int i=0; i <7; i++){
208            addTower(i+3,4);
209        }
210                */
211    }
212
213    // Generates a TowerDefenseEnemy. Uses Template "enemytowerdefense". Sets position at first waypoint of path.
214    void TowerDefense::addTowerDefenseEnemy(std::vector<TDCoordinate*> path, int templatenr){
215
216
217        TowerDefenseEnemy* en1 = new TowerDefenseEnemy(this->center_->getContext());
218       
219        switch(templatenr)
220        {
221        case 1 :
222            en1->addTemplate("enemytowerdefense1");
223            en1->setScale(3);
224            en1->setHealth(en1->getHealth() + this->getWaveNumber()*4);
225            break;
226
227        case 2 :
228            en1->addTemplate("enemytowerdefense2");
229            en1->setScale(2);
230            en1->setHealth(en1->getHealth() + this->getWaveNumber()*4);
231            //  en1->setShieldHealth(en1->getShield() = this->getWaveNumber()*2))
232            break;
233
234        case 3 :
235            en1->addTemplate("enemytowerdefense3");
236            en1->setScale(1);
237            en1->setHealth(en1->getHealth() + this->getWaveNumber()*4);
238            break;
239        }
240
241        en1->setTeam(2);
242        en1->getController();
243        en1->setPosition(path.at(0)->get3dcoordinate());       
244        TowerDefenseEnemyvector.push_back(en1);
245
246        for(unsigned int i = 0; i < path.size(); ++i)
247        {
248            en1->addWaypoint((path.at(i)));
249        }
250    }
251
252
253    void TowerDefense::end()
254    {
255
256        TeamDeathmatch::end();
257        ChatManager::message("Match is over! Gameover!");
258
259    }
260
261    void TowerDefense::spawnPlayer(PlayerInfo* player)
262    {
263        assert(player);
264        this->player_ = player;
265
266        if (selecter->getPlayer() == NULL)
267        {
268            this->player_ = player;
269            player->startControl(selecter);
270            players_[player].state_ = PlayerState::Alive;
271        } 
272    }
273
274    /**
275    @brief
276        Get the player.
277    @return
278        Returns a pointer to the player. If there is no player, NULL is returned.
279    */
280    PlayerInfo* TowerDefense::getPlayer(void) const
281    {
282        return this->player_;
283    }
284
285    //not working yet
286    void TowerDefense::upgradeTower(int x,int y)
287    {
288        TDCoordinate* coord = new TDCoordinate(x,y);
289        x = coord->GetX();
290        y = coord->GetY();
291       
292        const int upgradeCost = 20;
293
294        if (!this->hasEnoughCreditForTower(upgradeCost))
295        {
296            orxout() << "not enough credit: " << (this->getCredit()) << " available, " << upgradeCost << " needed.";
297            return;
298        }
299
300
301        Model* dummyModel2 = new Model(this->center_->getContext());
302
303        if (towerModelMatrix [x][y] == NULL || (towerModelMatrix [x][y])->getMeshSource() == dummyModel2->getMeshSource())
304        {
305            orxout() << "no tower on this position" << endl;
306            return;
307        }
308
309        else
310        {
311            (towerTurretMatrix [x][y])->upgradeTower();
312            this->buyTower(upgradeCost);
313        }
314    }
315
316    /*adds Tower at Position (x,y) and reduces credit and adds the point to the towermatrix. template ("towerturret")
317    so towers have ability if the turrets
318    */
319
320    void TowerDefense::addTower(int x, int y)
321    {       
322        TDCoordinate* coord = new TDCoordinate(x,y);
323        x = coord->GetX();
324        y = coord->GetY();
325
326        const int towerCost = 20;
327
328        if (!this->hasEnoughCreditForTower(towerCost))
329        {
330            orxout() << "not enough credit: " << (this->getCredit()) << " available, " << towerCost << " needed.";
331            return;
332        }
333
334        if (towerModelMatrix [x][y]!=NULL)
335        {
336            orxout() << "not possible to put tower here!!" << endl;
337            return;
338        }
339
340/*
341        unsigned int width = this->center_->getWidth();
342        unsigned int height = this->center_->getHeight();
343*/
344
345        int tileScale = (int) this->center_->getTileScale();
346
347        /*if (x > 15 || y > 15 || x < 0 || y < 0)
348        {
349            //Hard coded: TODO: let this depend on the centerpoint's height, width and fieldsize (fieldsize doesn't exist yet)
350            orxout() << "Can not add Tower: x and y should be between 0 and 15" << endl;
351            return;
352        }*/
353
354        //orxout() << "Will add tower at (" << (x-8) * tileScale << "," << (y-8) * tileScale << ")" << endl;
355        orxout() << "Will add tower at (" << x << "," << y << ")" << endl;
356
357
358        //Create Model
359        Model* newTowerModel = new Model(this->center_->getContext());
360        newTowerModel->setMeshSource("Tower.mesh");
361        newTowerModel->setScale(45);
362        newTowerModel->setPosition(static_cast<float>((x-8) * tileScale), static_cast<float>((y-8) * tileScale), 50);
363
364        //Creates tower
365        TowerDefenseTower* towernew = new TowerDefenseTower(this->center_->getContext());
366        towernew->setPosition(static_cast<float>((x-8) * tileScale), static_cast<float>((y-8) * tileScale), 275);
367        towernew->setGame(this);
368        towernew->setTeam(1);
369
370        //Reduce credit
371         this->buyTower(towerCost);
372         towerModelMatrix [x][y]= newTowerModel;
373         towerTurretMatrix [x][y]= towernew;
374    }   
375
376    bool TowerDefense::hasEnoughCreditForTower(int towerCost)
377    {
378        return ((this->getCredit()) >= towerCost);
379    }
380
381
382    bool TowerDefense::hasEnoughCreditForUpgrade()
383    {
384        return true;
385    }
386
387 
388    void TowerDefense::tick(float dt)
389    {
390        SUPER(TowerDefense, tick, dt);
391        time +=dt;
392
393        TDCoordinate* coord1 = new TDCoordinate(1,1);
394        std::vector<TDCoordinate*> path;
395        path.push_back(coord1);
396        if(time>=TowerDefenseEnemyvector.size() && TowerDefenseEnemyvector.size() < 30)
397        {
398            //adds different types of enemys depending on the WaveNumber
399            addTowerDefenseEnemy(path, this->getWaveNumber() % 3 +1 );
400        }
401
402        Vector3* endpoint = new Vector3(500, 700, 150);
403        //if ships are at the end they get destroyed
404        for(unsigned int i =0; i < TowerDefenseEnemyvector.size(); ++i)
405        {
406            if(TowerDefenseEnemyvector.at(i) != NULL && TowerDefenseEnemyvector.at(i)->isAlive())
407            {
408                //destroys enemys at the end of the path and reduces the life by 1. no credits gifted
409
410                Vector3 ship = TowerDefenseEnemyvector.at(i)->getRVWorldPosition();
411                float distance = ship.distance(*endpoint);
412
413                if(distance <50){
414                    TowerDefenseEnemyvector.at(i)->destroy();
415                    this->reduceLifes(1);
416                    this->buyTower(1);
417                    if (this->getLifes()==0)
418                    {
419                        this->end();
420                    }
421                }
422            }
423        }
424
425        //goes thorugh vector to see if an enemy is still alive. if not next wave is launched
426        int count= 0;
427        for(unsigned int i =0; i < TowerDefenseEnemyvector.size(); ++i)
428        {
429            if(TowerDefenseEnemyvector.at(i)!= NULL)
430            {
431                ++count;
432            }
433        }
434
435        if (count == 0 && !this->nextwaveTimer_.isActive())
436            this->nextwaveTimer_.startTimer();
437
438/*            time2 +=dt;
439        if(count== 0)
440        {
441            if(time2 > 10)
442            {
443                TowerDefenseEnemyvector.clear();
444                this->nextwave();
445                time=0;
446                time2=0;
447            }
448        }
449*/
450
451    }
452
453    // Function to test if we can add waypoints using code only. Doesn't work yet
454
455    // THE PROBLEM: WaypointController's getControllableEntity() returns null, so it won't track. How do we get the controlableEntity to NOT BE NULL???
456    /*
457    void TowerDefense::addWaypointsAndFirstEnemy()
458    {
459        SpaceShip *newShip = new SpaceShip(this->center_);
460        newShip->addTemplate("spaceshipassff");
461
462        WaypointController *newController = new WaypointController(newShip);
463        newController->setAccuracy(3);
464
465        Model *wayPoint1 = new Model(newController);
466        wayPoint1->setMeshSource("crate.mesh");
467        wayPoint1->setPosition(7,-7,5);
468        wayPoint1->setScale(0.2);
469
470        Model *wayPoint2 = new Model(newController);
471        wayPoint2->setMeshSource("crate.mesh");
472        wayPoint2->setPosition(7,7,5);
473        wayPoint2->setScale(0.2);
474
475        newController->addWaypoint(wayPoint1);
476        newController->addWaypoint(wayPoint2);
477
478        // The following line causes the game to crash
479
480        newShip->setController(newController);
481//        newController -> getPlayer() -> startControl(newShip);
482        newShip->setPosition(-7,-7,5);
483        newShip->setScale(0.1);
484        //newShip->addSpeed(1);
485
486
487
488//      this->center_->attach(newShip);
489    }
490    */
491    /*
492    void TowerDefense::playerEntered(PlayerInfo* player)
493    {
494        TeamDeathmatch::playerEntered(player);
495
496        const std::string& message = player->getName() + " entered the game";
497        ChatManager::message(message);
498    }
499
500    bool TowerDefense::playerLeft(PlayerInfo* player)
501    {
502        bool valid_player = TeamDeathmatch::playerLeft(player);
503
504        if (valid_player)
505        {
506            const std::string& message = player->getName() + " left the game";
507            ChatManager::message(message);
508        }
509
510        return valid_player;
511    }
512
513
514    void TowerDefense::pawnKilled(Pawn* victim, Pawn* killer)
515    {
516        if (victim && victim->getPlayer())
517        {
518            std::string message;
519            if (killer)
520            {
521                if (killer->getPlayer())
522                    message = victim->getPlayer()->getName() + " was killed by " + killer->getPlayer()->getName();
523                else
524                    message = victim->getPlayer()->getName() + " was killed";
525            }
526            else
527                message = victim->getPlayer()->getName() + " died";
528
529            ChatManager::message(message);
530        }
531
532        TeamDeathmatch::pawnKilled(victim, killer);
533    }
534
535    void TowerDefense::playerScored(PlayerInfo* player, int score)
536    {
537        Gametype::playerScored(player, score);
538    }*/
539}
Note: See TracBrowser for help on using the repository browser.