Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Added missmissing #include _.h Now the program compiles without any error.

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